<?php

namespace frontend\controllers;

use common\models\Category;
use common\models\Comment;
use common\models\UserCategory;
use common\WuMing;
use common\Yii01;
use frontend\models\ArticleForm;
use frontend\models\PicForm;
use frontend\models\PostForm;
use frontend\models\UrlForm;
use Yii;
use common\models\Post;
use common\models\search\PostSearch;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\Pagination;
use yii\filters\AccessControl;

/**
 * PostController implements the CRUD actions for Post model.
 */
class PostController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['pic', 'article', 'url','delete'],
                'rules' => [
                    [
                        //    'actions' => ['create', 'delete', 'update'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Post models.
     * @return mixed
     */
    public function actionIndex($cid, $type = null)
    {
        //判断参数是否正确
        if (!$cid) {
            throw new BadRequestHttpException("参数错误");
        }
        //判断是否存在此分类
        if (Category::findOne($cid) == null) {
            throw new NotFoundHttpException("分类不存在");
        }
        $query = Post::find();
        //根据类型显示内容
        $count = 0 ;
        if ($type == null) {
            $sql ="SELECT *,(post.zan-post.cai)/(POW((unix_timestamp(now())-post.create_at)/3600+2,1.5)) num FROM post WHERE post.status IN (1, 3, 4) AND post.cate_id={$cid} ORDER BY post.status DESC,num DESC";
            $q = Yii::$app->db->createCommand($sql)->queryAll();
            $pages = new Pagination([
                'totalCount' => count($q),
                'defaultPageSize' => 20
            ]);
            $model = Yii::$app->db->createCommand($sql." limit ".$pages->limit." offset ".$pages->offset."")->queryAll();
            $count = count($q);
        } elseif ($type == "article") {
            $post = $query->orderBy(['post.last_comment' => SORT_DESC])->asArray()->where(['type' => 1, 'post.status' => 1, 'cate_id' => $cid]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $count =$post->count();
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        }elseif ($type == "zy") {
            $post = $query->orderBy(['post.status'=>SORT_DESC,'post.cai' => SORT_DESC])->asArray()->where(['post.status' => [1,3,4], 'cate_id' => $cid]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $count =$post->count();
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "pic") {
            $post = $query->orderBy(['post.last_comment' => SORT_DESC])->asArray()->where(['type' => 2, 'post.status' => 1, 'cate_id' => $cid]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $count =$post->count();
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "url") {
            $post = $query->orderBy(['post.last_comment' => SORT_DESC])->asArray()->where(['type' => 3, 'post.status' => 1, 'cate_id' => $cid]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "new") {
            $post = $query->orderBy(['post.status'=>SORT_DESC,'id' => SORT_DESC])->asArray()->where(['post.status' => [1,3,4], 'cate_id' => $cid]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $count =$post->count();
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();

        } else {
            throw new BadRequestHttpException("参数错误！");
        }


        //获取分类信息
        $category = Category::findOne($cid);
        //判断用户是否已经订阅
        $dingyue = UserCategory::findOne(['user_id' => Yii::$app->user->id, 'cate_id' => $cid]);
        //将结果传递到视图
        return $this->render('index', [
            'model' => $model,
            'pages' => $pages,
            'type' => $type,
            'cid' => $cid,
            'count'=>$count,
            'category' => $category,
            'dingyue' => $dingyue,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id, $type = null)
    {
        $this->layout="view";

        $model = Post::findOne($id);
        //每浏览一次  次数+1
        $model->view += 1;
        $model->update();
        $query = Comment::find()->where(['post_id' => $model['id']]);


        $data = [];
        if ($type == 1) { //最新
            $data = $query->asArray()
                ->orderBy(['id' => SORT_DESC])
                ->all();
        } elseif ($type == 2) {
            $data = $query->asArray()
                ->orderBy(['id' => SORT_ASC])
                ->all();
        } elseif ($type == 3) {
            $data = $query->asArray()
                ->orderBy(['sum' => SORT_ASC])
                ->all();
        } else {
            $data = $query->asArray()
                ->orderBy(['sum' => SORT_DESC])
                ->all();
        }
        $comment = Yii01::tree($data);


        //  WuMing::dd($comment);die;
        return $this->render('view', [
            'model' => $model,
            'comment' => $comment,
            'type' => $type,
            'uid'=>$model->user_id
        ]);
    }

    public function actionDialog($id, $type = null)
    {
        $this->layout = "dialog";
        $data = [];
        $query = Comment::find()->where(['post_id' => $id]);
        if ($type == 1) { //最新
            $data = $query->asArray()
                ->orderBy(['id' => SORT_DESC])
                ->all();
        } elseif ($type == 2) {
            $data = $query->asArray()
                ->orderBy(['id' => SORT_ASC])
                ->all();
        } elseif ($type == 3) {
            $data = $query->asArray()
                ->orderBy(['sum' => SORT_ASC])
                ->all();
        } else {
            $data = $query->asArray()
                ->orderBy(['sum' => SORT_DESC])
                ->all();
        }
        $comment = Yii01::tree($data);
        $model = Post::findOne($id);
        //每浏览一次  次数+1
        $model->view += 1;
        $model->update();
        return $this->render('dialog', [
            'model' => $model,
            'comment' => $comment,
            'type' => $type,
            'uid'=>$model->user_id
        ]);
    }

    /**
     * Creates a new Post model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionArticle()
    {

        if(!Yii01::isHasCate()){
            return $this->redirect(Yii::$app->urlManager->createUrl("list/index"));
        }
        $blackList = Yii01::isBlackList();

        $model = new ArticleForm();
        if ($blackList) {
            Yii01::alert($blackList);
            return $this->render('article', [
                'model' => $model,
            ]);
        }
        if ($model->load(Yii::$app->request->post())) {
            if ($post = $model->createPost()) {
                return $this->redirect(['view', 'id' => $post->id]);
            }
        }
        return $this->render('article', [
            'model' => $model,
        ]);
    }

    public function actionPic()
    {
        if(!Yii01::isHasCate()){
            return $this->redirect(Yii::$app->urlManager->createUrl("list/index"));
        }
        $model = new PicForm();
        $blackList = Yii01::isBlackList();
        if ($blackList) {
            Yii01::alert($blackList);
            return $this->render('pic', [
                'model' => $model,
            ]);
        }
        if ($model->load(Yii::$app->request->post())) {
            $post = $model->createPost();
            if ($post) {
                return $this->redirect(['view', 'id' => $post->id]);
            }
        }
        return $this->render('pic', [
            'model' => $model,
        ]);
    }


    public function actionUrl()
    {
        if(!Yii01::isHasCate()){
            return $this->redirect(Yii::$app->urlManager->createUrl("list/index"));
        }

        $model = new UrlForm();
        $blackList = Yii01::isBlackList();
        if ($blackList) {
            Yii01::alert($blackList);
            return $this->render('url', [
                'model' => $model,
            ]);
        }
        if ($model->load(Yii::$app->request->post())) {
            if ($post = $model->createPost()) {
                return $this->redirect(['view', 'id' => $post->id]);
            }
        }
        return $this->render('url', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Post model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate()
    {
        return $this->goHome();
//        $model = $this->findModel($id);
//
//        if ($model->load(Yii::$app->request->post()) && $model->save()) {
//            return $this->redirect(['view', 'id' => $model->id]);
//        } else {
//            return $this->render('update', [
//                'model' => $model,
//            ]);
//        }
    }

    /**
     * Deletes an existing Post model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {

        $post = $this->findModel($id);
        if (Yii::$app->user->can('admin_login') || Yii01::isManager(Yii::$app->user->id, $post->cate_id)) {
            $post->status = -1;
            $post->save();
        }
        return $this->redirect(['site/index']);
    }

    /**
     * Finds the Post model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Post::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}